<script setup lang="ts">
import { ref } from 'vue'
import type { PostPatientAddParams } from '@/types/subpkg'
import { postPatientAddAPI, getPatientInfoByIdAPI, putPatientUpdateAPI } from '@/apis/subpkg'
import { onLoad, onReady } from '@dcloudio/uni-app'

const formData = ref<PostPatientAddParams>({
  name: '',
  idCard: '',
  gender: 1,
  defaultFlag: 1,
})

const formRules = ref<UniHelper.UniFormsRules>({
  name: {
    rules: [
      { required: true, errorMessage: '请填写患者姓名' },
      { pattern: /^(?:[\u4e00-\u9fa5·]{2,16})$/, errorMessage: '请输入中文姓名' },
    ],
  },
  idCard: {
    rules: [
      { required: true, errorMessage: '请填写患者身份证号' },
      {
        pattern:
          /^[1-9]\d{5}(?:18|19|20)\d{2}(?:0[1-9]|10|11|12)(?:0[1-9]|[1-2]\d|30|31)\d{3}[\dXx]$/,
        errorMessage: '请输入正确的身份证号',
      },
    ],
  },
  gender: {
    rules: [
      { required: true, errorMessage: '请选择患者性别' },
      {
        // 自定义校验规则
        validateFunction: (rule, value, data, callback) => {
          const idCardGenderNumber = formData.value.idCard.charAt(16)
          // 判断身份证第 17 位(索引为16)是否与选择的性别一致
          if (Number(idCardGenderNumber) % 2 !== value) {
            // callback 处理提示错误信息
            callback('选择的性别与身份号中性别不一致')
          }
          return true
        },
      },
    ],
  },
})

// 3. 校验表单
const formRef = ref<UniHelper.UniFormsInstance>()
const onSubmit = async () => {
  // 校验表单
  await formRef.value?.validate?.()
  // 如果页面参数有 id，调用编辑接口，否则调用添加接口
  if (props.id) {
    const { name, idCard, gender, defaultFlag, id } = formData.value
    await putPatientUpdateAPI({ name, idCard, gender, defaultFlag, id })
  } else {
    // 调用接口，注意：一个帐号最多添加 6 个患者
    await postPatientAddAPI(formData.value)
  }
  // 跳转回患者列表页
  uni.navigateBack()
  uni.showToast({ title: '添加成功', icon: 'success' })
}

// 4. Switch 开关组件切换事件
const onChangeDefaultFlag = (event: UniHelper.SwitchOnChangeEvent) => {
  formData.value.defaultFlag = event.detail.value ? 1 : 0
}

// 5. 接收页面参写法1
onLoad((options) => {
  console.log('页面加载时获取页面参数', options)
})

// 5. 接收页面参写法2-更方便
const props = defineProps<{ id?: string }>()
console.log('页面级组件，可通过 props 接收页面参数', props)
onReady(() => {
  // 动态设置导航栏标题，写到 onReady 中兼容性更好，避免小程序端偶尔出现无法修改的情况
  uni.setNavigationBarTitle({ title: props.id ? '编辑患者' : '添加患者' })
})

// 获取患者详情
const getPatientInfoById = async () => {
  // 如果 props.id 存在，则查询患者详情
  if (props.id) {
    const res = await getPatientInfoByIdAPI(props.id)
    // 保存患者信息，在表单中回显
    formData.value = res.data
  }
}
getPatientInfoById()
</script>

<template>
  <scroll-view>
    <view class="archive-page">
      <uni-forms border label-width="220rpx" ref="formRef" :model="formData" :rules="formRules">
        <uni-forms-item label="患者姓名" name="name">
          <uni-easyinput
            placeholder-style="color: #C3C3C5; font-size: 32rpx"
            :input-border="false"
            :clearable="false"
            placeholder="请填写真实姓名"
            v-model="formData.name"
          />
        </uni-forms-item>
        <uni-forms-item label="患者身份证号" name="idCard">
          <uni-easyinput
            placeholder-style="color: #C3C3C5; font-size: 32rpx"
            v-model="formData.idCard"
            :input-border="false"
            :clearable="false"
            placeholder="请填写身份证号"
          />
        </uni-forms-item>
        <uni-forms-item label="患者性别" name="gender">
          <uni-data-checkbox
            v-model="formData.gender"
            selectedColor="#16C2A3"
            :localdata="[
              { text: '男', value: 1 },
              { text: '女', value: 0 },
            ]"
          />
        </uni-forms-item>
        <uni-forms-item label="默认就诊人" name="">
          <view class="uni-switch">
            <switch
              :checked="formData.defaultFlag == 1"
              color="#20c6b2"
              style="transform: scale(0.7)"
              @change="onChangeDefaultFlag"
            />
          </view>
        </uni-forms-item>
        <button class="uni-button" @click="onSubmit">保存</button>
      </uni-forms>
      {{ formData.name }}
      {{ formData.idCard }}
      {{ formData }}
    </view>
  </scroll-view>
</template>

<style lang="scss">
@import './index.scss';
</style>
